<?php

class PageController extends BaseController {

  public function addPage() {
    $page                 = new Page;
    $page->title          = Input::get('name');
    $page->tempestuser_id = Auth::user()->id;

    // get order:
    $order = Auth::user()->pages()->max('order');
    $max   = is_null($order) ? 1 : $order + 1;

    // save and redirect.
    $page->order = $max;

    $validator = Validator::make($page->toArray(), Page::$rules);
    if (!$validator->fails()) {
      $page->save();
      Session::flash('currentPage', $page->id);
      Session::flash('success', 'New tab created!');
      return Redirect::to('/');
    }
    Session::flash('error', $validator->messages()->first());
    return Redirect::to('/');
  }

  public function deletePage() {
    $page = Auth::user()->pages()->find(intval(Input::get('id')));
    if ($page) {
      $page->delete();
      Session::flash('success', 'Tab deleted');
    } else {
      Session::flash('error', 'Could not delete tab.');
    }
    return Redirect::to('/');
  }

  public function editPage() {
    $page = Auth::user()->pages()->find(intval(Input::get('id')));
    if ($page) {
      $page->title = Input::get('title');

      $validator = Validator::make($page->toArray(), Page::$rules);
      if (!$validator->fails()) {
        $page->save();
        Session::flash('currentPage', $page->id);
        Session::flash('success', 'Tab edited!');
        return Redirect::to('/');
      }
      Session::flash('error', $validator->messages()->first());
      return Redirect::to('/');
    }
    Session::flash('error', 'Could not edit Tab');
    return Redirect::to('/');
  }

  public function sortPage() {
    $page = Auth::user()->pages()->find(intval(Input::get('id')));
    if ($page) {
      $page->order = intval(Input::get('order'));
      $validator   = Validator::make($page->toArray(), Page::$rules);
      if (!$validator->fails()) {
        $page->save();
        return Response::json(true);
      }
      return Response::json(false);
    }
  }

  public function getInfo() {
    $page = Auth::user()->pages()->find(intval(Input::get('id')));
    if ($page) {
      return Response::json($page->toArray());
    }
    return App::abort(404);
  }

}